package com.woniuxy.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @ClassName JWTUtils
 * @Description TODO
 * @Author LI.hh
 * @Date 2022/9/5 19:39
 * @Version 1.0
 */
public class JWTUtils {
    private static final String SECURITY="WONIU";
    private static final long EXPIRES = 30*1000*60;

    /**
     * 生产token
     * @param username
     * @return
     */
    public static String sign(String username,String password){
        long exTime = System.currentTimeMillis()+EXPIRES;
        return JWT.create().withClaim("username",username).withExpiresAt(new Date(exTime)).sign(Algorithm.HMAC256(username+password+SECURITY));
    }

    /**
     * 返回用户名信息
     * @param token
     * @return
     */
    public static String getUsername(String token){
        DecodedJWT decode= JWT.decode(token);
        return decode.getClaim("username").asString();
    }

    /**
     * 判断之前的token有没有被篡改
     * @param token
     * @param username
     * @return
     */
    public static boolean verify(String token,String username,String password){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(username+password+SECURITY)).withClaim("username", username).build();
        jwtVerifier.verify(token);
        return true;
    }

}
